import mqtt from 'mqtt'
const mqttUrl = import.meta.env.VITE_APP_MQTT

export default {
  connection: {
    host: mqttUrl,
    // host: "115.231.114.182",
    port: 8084,
    connectTimeout: 4000, // 超时时间
    reconnectPeriod: 4000, // 重连时间间隔
    protocol: 'wss',
  },
  client: {
    connected: false,
  },
  Uint8ArrayToString: function (fileData) {
    var decoder = new TextDecoder('utf-8');
    return decoder.decode(fileData);
  },
  // 创建连接
  createConnection: function (topicList) {
    return new Promise((r) => {
      const { host, port, ...options } = this.connection
      const connectUrl = `wss://${host}:${port}/mqtt`
      try {
        this.client = mqtt.connect(connectUrl, options)
        this.client.on('connect', () => {
          console.log('Connection succeeded!')
          for (let item of topicList) {
            this.client.subscribe(item.topic, (err) => {
              if (!err) {
                console.log("订阅成功");
              }
            });
          }
        })
        this.client.on('error', error => {
          console.log('Connection failed', error)
        })
        r(this.client)
      } catch (error) {
        console.log('mqtt.connect error', error)
      }
    })
  },
  sendMessage: function (topic, data) {
    this.client.publish(topic, JSON.stringify(data));
  }
}